#@revision $Revision$ 
#@author Jorge Niedbalski R. <jnr@niedbalski.org>

from Listener      import Listener
from TaskManager  import TaskManager
from Config          import Config

import os
import sys
import simplejson as json
import Queue

class    SCQueue:

    exceptionQueue = Queue.Queue()

    _listener     = None
    _taskManager  = None

    def   _init_(self):

        try:
            self.restartQueues()
        except Exception as e:
            self.stop()

        self._listener    = Listener(self.exceptionQueue)
        self._taskManager = TaskManager(self.exceptionQueue, Config.getWorkers())
            
    def   start(self):
        
        #set the threads names
        self._listener.setName('http listener')
        self._taskManager.setName('task manager')

        #start task manager and http listener
        self._listener.start()
        self._taskManager.start()

        while True:
            try:
                exc = self.exceptionQueue.get(block=False)
            except Queue.Empty:
                pass
            else:
                print exc
                self.stop()                

    def   stop(self):
        if self._listener.isAlive():
            #stop the main tornado ioloop
            if Config.DEBUG:
                print "Terminating http listener thread: %s" % ( self._listener
            self._listener.stop()

        if self._taskManager.isAlive():
            if Config.DEBUG:
                print "Terminating task manager thread: %s" % ( self._taskManager
            self._taskManager.stop()
        #stop the main thread
        sys.exit()

    def   restartQueues(self):
        queues = Config.getQueues()
        if queues:
            for queue in Config.getQueues():
                directory = Config.getQueuesPath() + queue
                if not (os.path.exists(directory) and os.path.isdir(directory) == True):
                    raise Exception("Invalid queue directory %s" % ( directory)
                filelist  = os.listdir(directory)
                if filelist._len_():
                    for file in filelist:
                        spool = directory + "/" + file
                        fd    = open(spool, "r+")
                        if not fd:
                            raise Exception("Invalid task %s on queue directory %s" % ( file, directory)
                        readed = fd.read()
                        if not readed:    
                            raise Exception("Cannot read data from task %s from directory : %s" % ( file, directory)
                        TaskManager.addTaskToQueueFromListener(readed, file)
                        fd.close()
